package com.java.sevice.impl;

import com.alibaba.fastjson.JSONObject;
import com.java.dto.ResultMsg;
import com.java.remoteInterface.Bank1Service;
import com.java.remoteInterface.Bank2Service;
import com.java.sevice.ITransferService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Slf4j
public class TransferServiceImpl implements ITransferService {
    @Autowired
    Bank1Service bank1Service;
    @Autowired
    Bank2Service bank2Service;


    /**
     * 转账
     *
     * @param accountId 用户账户
     * @param amount    转账金额
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @HmilyTCC(confirmMethod = "confirmTransfer", cancelMethod = "cancelTransfer")
    public ResultMsg transferMoney(Long accountId, BigDecimal amount) {
        log.info("transfer-service 开始转账 start...");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountId", accountId);
        jsonObject.put("amount", amount);
        bank1Service.tryTransfer(jsonObject);
        bank2Service.tryTransfer(jsonObject);
        return ResultMsg.ok("ok");
    }


    @Override
    public ResultMsg confirmTransfer(Long accountId, BigDecimal amount) {
        log.info("transfer-service 确认转账 start...");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountId", accountId);
        jsonObject.put("amount", amount);
        bank1Service.confirmTransfer(jsonObject);
        bank2Service.confirmTransfer(jsonObject);
        return ResultMsg.ok("ok");
    }

    @Override
    public ResultMsg cancelTransfer(Long accountId, BigDecimal amount) {
        log.info("transfer-service 取消转账 start...");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountId", accountId);
        jsonObject.put("amount", amount);
        bank1Service.cancelTransfer(jsonObject);
        bank2Service.cancelTransfer(jsonObject);
        return ResultMsg.ok("ok");
    }
}